import React from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Eye, ChevronDown, ChevronRight, Lightbulb, Cpu, ClipboardCheck, Info, CheckCircle2 } from 'lucide-react';
import { RichContent } from './RichContent';
import type { ActionLogSection } from '@/lib/langgraph-chat-ui';

interface ActionGroupProps {
  action: any;
  status: string;
  content: string;
  timestamp: string;
  onToggleCollapse: () => void;
  isCollapsed: boolean;
  sections?: ActionLogSection[];
  onToggleSection: (sectionId: string) => void;
}

export function ActionGroup({ 
  action, 
  status, 
  content, 
  timestamp, 
  onToggleCollapse, 
  isCollapsed,
  sections = [],
  onToggleSection
}: ActionGroupProps) {
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'text-gray-400';
      case 'active': return 'text-yellow-400';
      case 'completed': return 'text-green-400';
      case 'failed': return 'text-red-400';
      default: return 'text-gray-400';
    }
  };

  const executorLabel = action?.agent_id || action?.executor_id || action?.type || '未指定';
  const actionSummary = action?.description || action?.goal || '';

  const renderSectionIcon = (type: ActionLogSection['type']) => {
    switch (type) {
      case 'think':
        return <Lightbulb className="w-4 h-4 text-amber-300" />;
      case 'tool':
        return <Cpu className="w-4 h-4 text-sky-300" />;
      case 'observation':
        return <ClipboardCheck className="w-4 h-4 text-emerald-300" />;
      case 'result':
        return <CheckCircle2 className="w-4 h-4 text-green-400" />;
      default:
        return <Info className="w-4 h-4 text-gray-300" />;
    }
  };

  return (
    <div className="flex justify-start">
      <div className="max-w-[80%] bg-white/10 border border-white/20 rounded-2xl p-4">
        <div 
          className="flex items-center justify-between cursor-pointer hover:bg-white/5 rounded-lg p-2 -m-2"
          onClick={onToggleCollapse}
        >
          <div className="flex items-center gap-2">
            {isCollapsed ? (
              <ChevronRight className="w-4 h-4" />
            ) : (
              <ChevronDown className="w-4 h-4" />
            )}
            <div className="flex flex-col">
              <span className="font-semibold text-sm">
                {action.action_id} · {executorLabel}
              </span>
              {actionSummary && (
                <span className="text-xs opacity-70 max-w-xs">{actionSummary}</span>
              )}
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <span className={`text-xs ${getStatusColor(status)}`}>
              {status === 'pending' ? '待执行' : 
               status === 'active' ? '执行中' : 
               status === 'completed' ? '已完成' : '执行失败'}
            </span>
            <span className="text-xs opacity-60">{timestamp}</span>
            
            <Dialog>
              <DialogTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6 text-white/60 hover:text-white hover:bg-white/10"
                >
                  <Eye className="h-3 w-3" />
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>Prompt 详情</DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <h4 className="font-semibold mb-2">Action 信息</h4>
                    <div className="bg-gray-100 p-3 rounded-lg text-sm text-black">
                      <RichContent
                        content={"```json\n" + JSON.stringify(action, null, 2) + "\n```"}
                        className="text-black"
                        monospaceHeight={220}
                      />
                    </div>
                  </div>
                  <div>
                    <h4 className="font-semibold mb-2">系统提示</h4>
                    <div className="bg-gray-100 p-3 rounded-lg text-sm text-black">
                      <RichContent
                        content={Array.isArray(action.systemPrompt) ? action.systemPrompt.join('\n') : (action.systemPrompt || '无系统提示')}
                        className="text-black"
                      />
                    </div>
                  </div>
                  <div>
                    <h4 className="font-semibold mb-2">执行结果</h4>
                    <div className="bg-gray-100 p-3 rounded-lg text-sm text-black">
                      <RichContent content={content} className="text-black" monospaceHeight={260} />
                    </div>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </div>
        
        {!isCollapsed && (
          <div className="mt-3 space-y-3">
            {sections.length > 0 ? (
              sections.map((section) => (
                <div key={section.id} className="border border-white/10 rounded-xl bg-black/20">
                  <button
                    type="button"
                    onClick={() => onToggleSection(section.id)}
                    className="w-full flex items-center justify-between px-3 py-2 hover:bg-white/5 rounded-t-xl"
                  >
                    <div className="flex items-center gap-2 text-left">
                      {renderSectionIcon(section.type)}
                      <div className="flex flex-col">
                        <span className="text-sm font-medium">{section.title}</span>
                        {section.timestamp && (
                          <span className="text-xs text-white/50">{section.timestamp}</span>
                        )}
                      </div>
                    </div>
                    {section.isCollapsed ? (
                      <ChevronRight className="w-4 h-4" />
                    ) : (
                      <ChevronDown className="w-4 h-4" />
                    )}
                  </button>
                  {!section.isCollapsed && (
                    <div className="px-3 pb-3 pt-1">
                      <RichContent content={section.content} className="text-sm opacity-90" />
                    </div>
                  )}
                </div>
              ))
            ) : (
              content && (
                <RichContent content={content} className="text-sm opacity-90" />
              )
            )}
          </div>
        )}
      </div>
    </div>
  );
}
